/**
 * @brief Joystick driver implementation
 * @author Gilad Avidov
 */

#include <mcs51/8051.h>
#include <mcs51/at89c51ed2.h>  //also includes 8052.h and 8051.h
#include <mcs51reg.h>
#include <stdio.h>
#include "MCP3002.h"
#include "joystick.h"

#define X_CHNL     (1)
#define Y_CHNL     (0)

static short joystick_x_center;
static short joystick_y_center;
volatile bit joystick_was_pressed = 0;

void joystick_center()
{
    joystick_x_center = mcp_read(X_CHNL);
    joystick_y_center = mcp_read(Y_CHNL);
    printf("joystick center-at x:%d y:%d\n\r", joystick_x_center, joystick_y_center);
}

bit joystick_button_pressed()
{
    bit prev = joystick_was_pressed;
    joystick_was_pressed = 0;
    JOYSTICK_INTERRUPT_ENABLE = 1;
    return prev;
}

void joystick_init()
{
    mcp_init(1);
    joystick_center();
    JOYSTICK_INTERRUPT_ENABLE = 1;    // enable interrupt from button
}

short joystick_get_x()
{
    return  mcp_read(X_CHNL) - joystick_x_center;
}

short joystick_get_y()
{
    return  mcp_read(Y_CHNL) - joystick_y_center;
}
